//
//  DiagnosisViewController.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "DiagnosisViewController.h"
#import "DiagnosisCell.h"
#import "WIFIHelper.h"
#import "HelpViewController.h"
#import "DiscoverNewWIFIController.h"
@interface DiagnosisViewController ()

@property (nonatomic, strong)   UIScrollView *scrollView;
@property (nonatomic, strong)   UIButton *scanButton;
@property (nonatomic, strong)   UILabel *resultLabel;
@property (nonatomic, strong)   WIFIHelper *wifiHelper;


@property (nonatomic, strong)CAShapeLayer *progressLayer;
@property (nonatomic, strong)UIBezierPath *progressPath;
/// 已完成的进度
@property (nonatomic, assign)CGFloat completedProgress;
/// 进度
@property (nonatomic, assign)CGFloat progress;

@property (nonatomic, assign)BOOL animated;
/// 定时器
@property (nonatomic, strong)NSTimer *timer;

@property (nonatomic, strong) UIWebView *bgView;
@end

@implementation DiagnosisViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.wifiHelper = [[WIFIHelper alloc] init];
    
    self.navigationItem.title = @"智能网络诊断";
    
    
//    [self loginRequestShowData:NO];
    [self initUI];
    
    

}

-(void)initUI
{
    [self setTableViewStyle:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = [self getTableHeadView];
}


- (UIWebView *)bgView
{
    if (!_bgView)
    {
        // 读取gif图片数据
        NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"animation2" ofType:@"gif"]];
        _bgView = [[UIWebView alloc] init];
        _bgView.userInteractionEnabled = NO;//用户不可交互
        _bgView.scalesPageToFit  = YES;
        [_bgView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    }
    return _bgView;

}


-(UIView *)getTableHeadView
{
    UIImage *bgImage = [UIImage imageNamed:@"scan_bgk"];
    CGFloat bgScale = bgImage.size.width/bgImage.size.height;   //宽高比
    CGFloat h = ScreenWidth / bgScale;                          //图片等比例高
    CGFloat scale = (h/bgImage.size.height);                    //压缩\拉伸比例
    
    UIImage *scanImage = [UIImage imageNamed:@"scan_start_btn"];
    CGSize size = scanImage.size;
    size.height *= scale;
    size.width *= scale;
    
    
    CGFloat head_height = h + size.height/2 + 50;
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, head_height)];
    
    // view生成
    [headView addSubview:self.bgView];
    [self.bgView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.offset(h);
    }];
    
    //中间扫描按钮
    self.scanButton = [headView addButtonWithTitle:@"开始诊断" target:self action:@selector(scanButtonClicked:)];
    [_scanButton setTitleColor:COLOR_BASE forState:UIControlStateNormal];
    [_scanButton setBackgroundImage:scanImage forState:UIControlStateNormal];
    _scanButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [_scanButton makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.top.equalTo(self.bgView.bottom).offset(-size.height/2);
        make.size.mas_equalTo(size);
    }];
    
    
    _progressLayer = [CAShapeLayer new];
    _progressLayer.frame = self.scanButton.bounds;
    [self.scanButton.layer addSublayer:_progressLayer];
    _progressLayer.lineWidth = 5.0;
    _progressLayer.fillColor = [UIColor clearColor].CGColor;
    _progressLayer.strokeColor = [UIColor redColor].CGColor;
    _progressLayer.hidden = YES;
    
    //右小按钮
    CGFloat tip_width = 50*scale;
    UIView *tipBoxView = [UIView new];
    [headView addSubview:tipBoxView];
    [tipBoxView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_scanButton.right).offset(0);
        make.right.equalTo(self.bgView.right).offset(0);
        make.height.offset(tip_width);
        make.centerY.equalTo(_scanButton);
    }];
    
    UIButton *tipButton = [tipBoxView addButtonWithTitle:@"?" target:self action:@selector(tipButtonClicked:)];
    [tipButton setTitleColor:COLOR_BASE forState:UIControlStateNormal];
    [tipButton setBackgroundImage:[UIImage imageNamed:@"scan_start_btn"] forState:UIControlStateNormal];
    tipButton.titleLabel.font = [UIFont systemFontOfSize:25];
    [tipButton makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.centerX.equalTo(tipBoxView);
        make.size.mas_equalTo(Size(tip_width, tip_width));
        if ([self.contentList count] == 0) {
            
        }
    }];
    
    if ([self.contentList count] != 0) {
        WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
        NSString *string = [NSString stringWithFormat:@"%@有%ld个子WIFI",wifi.ssid,        (long)[self.contentList count]];
        self.resultLabel = [headView addLabelWithText:string font:[UIFont systemFontOfSize:20] color:[UIColor grayColor]];
        _resultLabel.textAlignment = NSTextAlignmentCenter;
        [_resultLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(30);
            make.right.offset(-30);
            make.top.equalTo(_scanButton.bottom).offset(15);
        }];
    }

    return headView;
}

-(void)scanButtonClicked:(UIButton *)sender
{
//    if (_progressLayer) {
//        [_progressLayer removeFromSuperlayer];
//        _progressLayer = nil;
//    }
//
    
    [self.contentList removeAllObjects];
    [self.tableView reloadData];
    [self loginRequestShowData:YES];

    
}

- (void)setProgress
{
    _progressPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.scanButton.bounds.size.width/2, self.scanButton.bounds.size.width/2) radius:((self.scanButton.bounds.size.width - 20)/2) startAngle:-M_PI/2 endAngle:M_PI*2*_completedProgress - M_PI/2 clockwise:YES];
    _progressLayer.path = _progressPath.CGPath;
}




- (void)setProgress:(CGFloat)progress
{
    [self setProgress:progress animated:NO];
}

- (void)setProgress:(CGFloat)progress animated:(BOOL)animated
{
    _progressLayer.hidden = NO;
    _progress = progress;
    _animated = animated;
    if (animated) {
        _completedProgress = 0.0f;
        [self startTimer];
    }
    else
    {
        [self setCompletedProgress:progress];
    }
}


#pragma mark -
#pragma mark    定时器
- (void)startTimer
{
    if ([_timer isValid])
    {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer timerWithTimeInterval:0.03 target:self selector:@selector(timeFireFunction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    
}


- (void)timeFireFunction
{
    
    if ( ABS(_progress - _completedProgress) > 0.000001) {
        _completedProgress +=0.01;
        [self setCompletedProgress:_completedProgress];
    }
    else{
        [self setCompletedProgress:_progress];
        [_timer invalidate];
        _timer  = nil;
        [self.scanButton setTitle:@"开始诊断" forState:UIControlStateNormal];
        self.scanButton.titleLabel.font = [UIFont systemFontOfSize:20];
        _progressLayer.hidden = YES;
    }
}




- (void)setCompletedProgress:(CGFloat)completedProgress
{
    _completedProgress = completedProgress;
    NSString *string = [NSString stringWithFormat:@"%0.0f%%",completedProgress*100];
    [self.scanButton setTitle:string forState:UIControlStateNormal];
    _scanButton.titleLabel.font = [UIFont systemFontOfSize:25];
    [self setProgress];
    
}


-(void)tipButtonClicked:(UIButton *)sender
{
    [self pushViewControllerWithClassName:@"HelpViewController"];
}


- (void)findNewWIFINotification:(NSNotification *)notify
{
    BOOL hasNewWIFI = [[notify object] boolValue];
    if (hasNewWIFI) {
        [self addLeftBarButtonWithNormalImageName:@"home_location" selectedImageName:@"home_location_pre" target:self action:@selector(leftButtonPressed:)];
    }
    self.navigationItem.leftBarButtonItem.customView.hidden = !hasNewWIFI;
}


- (void)leftButtonPressed:(id)sender
{
    NSLog(@"___func:%s__",__func__);
    DiscoverNewWIFIController *discoverNewWIFI = [[DiscoverNewWIFIController alloc] init];
    discoverNewWIFI.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:discoverNewWIFI animated:YES];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TK_FindNewWIFINotification object:nil];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFINotification:) name:TK_FindNewWIFINotification object:nil];
}




#pragma mark UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.contentList count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell1";
    DiagnosisCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell == nil) {
        cell = [[DiagnosisCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.contentList[indexPath.section];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)showOffLineView
{
    WEAKSELF
    [self showNetworkExceptionWithView:self.view andTitle:@"连不上网络了!" andButtonTitle:@"点击重试" andBtnBlock:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf loginRequestShowData:NO];
    }];
}

- (void)loginRequestShowData:(BOOL)showData
{
    UserModel *user = [UserSingleton shareInstance].userModel.user[0];
    
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    
    NSString *phone = user.userName;
    
    if (!showData) {
        self.activity = [self startActivityWithTitle:@""];
    }
    WEAKSELF
    
    [self.wifiHelper refreshDataWithDeviceID:wifi.device_id userName:phone success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (succ) {
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            LoginResponseModel *model = [LoginResponseModel objectWithKeyValues:responseObject];
            if ([model.wifi.status isEqualToString:@"offline"]) {
                [strongSelf showOffLineView];
            }
            else{
                if (showData) {
                    __block NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
                    [model.stations enumerateObjectsUsingBlock:^(StationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (!obj.master) {
                            [array addObject:obj];
                        }
                    }];
                    strongSelf.contentList = [NSMutableArray arrayWithArray:array];
                    [strongSelf.tableView reloadData];
                    strongSelf.tableView.tableHeaderView = [strongSelf getTableHeadView];
                    [self setProgress:1.0 animated:YES];
                    
                }
            }
        }
        else{
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            [strongSelf showOffLineView];
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf showOffLineView];
    }];
}
@end
